package ${package.Task}.cycle;

import javax.annotation.Resource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import ${package.Dao}.${entity}EsDao;
import ${package.Entity}.${entity};
import ${package.Entity}.${entity}Es;
import ${package.Service}.${table.serviceName};
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * ${table.comment!} => 增量同步到 Elasticsearch
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Slf4j
@Component
public class IncrSync${entity}ToEs {

    @Resource
    private ${table.serviceName} ${table.layuiServiceName};

    @Resource
    private ${entity}EsDao ${table.layuiEntityName}EsDao;

    /**
     * 每分钟执行一次
     */
    @Scheduled(fixedRate = 60 * 1000)
    public void run() {
        // 查询近 5 分钟内的数据
        Date fiveMinutesAgoDate = new Date(new Date().getTime() - 5 * 60 * 1000L);
        List<${entity}> list = ${table.layuiServiceName}.list(new QueryWrapper<${entity}>().le("${table.layuiTimeColumn.name}", fiveMinutesAgoDate));
        if (list.isEmpty()) return;
<#assign entityEs = entity + 'Es' />
        List<${entityEs}> esList = list.stream().map(${entity} :: transform).collect(Collectors.toList());
        final int pageSize = 500;
        int total = esList.size();
        log.info("IncSync${entity}ToEs start, total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            log.info("sync from {} to {}", i, end);
            ${table.layuiEntityName}EsDao.saveAll(esList.subList(i, end));
        }
        log.info("IncSync${entity}ToEs end, total {}", total);
    }

}
